<template>
  <el-card>
    <div class="app-container">
      <div class="search-container">
        <!-- 头部查询表单 -->
        <el-form ref="QueryFormRef" :model="params" style="display: flex;justify-content: space-between">
          <el-form-item>
            <el-button type="primary" @click="resetQuery">
              <el-icon>
                <refresh/>
              </el-icon>
              查询全部
            </el-button>
            <el-button :disabled="selectionIds.length === 0" style="margin-left: 1rem" type="danger"
                       @click="handleBatchDelete">
              <el-icon>
                <delete/>
              </el-icon>
              批量删除
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-card shadow="never">
        <el-table v-loading="orderTableLoading" :data="orderDataList"
                  :span-method="objectSpanMethod" border highlight-current-row
                  @selection-change="handleSelectionChange" @row-click="handleRowClick"
        >
          <el-table-column align="center" type="selection" width="55"/>
          <el-table-column align="center" label="报价" prop="quotation" width="150"/>
          <el-table-column align="center" label="付款" prop="payment" width="150"/>
          <el-table-column align="center" label="交易金额" prop="totalAmount" width="150"/>
          <el-table-column align="center" label="状态" width="150">
            <template #default="scope">
              <el-tag :type="status[scope.row.status-1].type" style="margin-bottom: 0.5em">
                {{ status[scope.row.status - 1].value }}
              </el-tag>
              <el-tag v-if="scope.row.status !== 7" :type="cancel[scope.row.cancel].type">
                {{ cancel[scope.row.cancel].value }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="备注" min-width="300" prop="remarks"/>
          <el-table-column :formatter="formatter" align="center" label="创建时间" prop="ctime" width="150"/>
          <el-table-column :formatter="formatter" align="center" label="完成时间" prop="dtime" width="150">
            <template #default="scope">
              {{scope.row.dtime}}
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="150">
            <template #default="scope">
              <el-button link size="small" type="primary" @click.stop="handleOrderStatus(scope.row)">
                <el-icon>
                  <edit/>
                </el-icon>
                订单状态
              </el-button>
              <el-button link size="small" type="primary" @click.stop="handleCancelOrder(scope.row)">
                <el-tooltip placement="top">
                  <template #content>若已付款，则将自动退款</template>
                  <el-icon>
                    <info-filled/>
                  </el-icon>
                </el-tooltip>
                申请取消订单
              </el-button>
              <el-button link size="small" type="primary" @click.stop="handleDelete(scope.row)">
                <el-icon>
                  <delete/>
                </el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-if="total > 0"
            v-model:page="params.page"
            v-model:size="params.size"
            v-model:total="total"
            @pagination="handleQuery"
        />
      </el-card>
    </div>
  </el-card>
</template>

<script setup>
import {onActivated, onMounted, reactive, ref} from "vue";
import {Delete, Edit, InfoFilled, Refresh} from "@element-plus/icons-vue";
import pagination from "@/components/pagination.vue";
/**
 * Order ——> 实体大驼峰
 * order ——> 实体小驼峰
 * 订单 ——> 实体中文名
 */
import {deleteOrderBatchByIds, getMyOrderPageList, toqcancel,} from "@/apis/order";
import router from "@/router/index.js";
import {formatter} from "@/utils/utils.js";
import {useOrderDetailsStore} from "@/stores/order.js";

const orderDetailsStore = useOrderDetailsStore();

const QueryFormRef = ref();
const orderTableLoading = ref(false);
const selectionIds = ref([]);

const total = ref(0);

const params = reactive({
  page: 1,
  size: 10
});

const orderDataList = ref([]);
const dialog = reactive({
  title: "",
  visible: false,
});

const status = [
  {key: 1, value: "创建", type: "primary", router: "create"},
  {key: 2, value: "申请报价", type: "primary", router: "appquotation"},
  {key: 3, value: "报价完成", type: "success", router: "finishquotation"},
  {key: 4, value: "完成支付", type: "success", router: "pay"},
  {key: 5, value: "打印中", type: "primary", router: "printing"},
  {key: 6, value: "打印完成", type: "success", router: "finishprint"},
  {key: 7, value: "订单完成", type: "success", router: "finishorder"}
]
const cancel = [
  {key: 0, value: "订单正在进行", type: "primary"},
  {key: 1, value: "申请取消订单中", type: "warning", router: "cancelorder"},
  {key: 2, value: "商家已同意退单", type: "success"},
  {key: 3, value: "取消订单被驳回", type: "danger"}
]
const mergeObj = ref({})
const mergeArr = reactive(['materialName', 'materialColor', 'name', 'subjects', 'score'])
//计算需要合并的数据
const getSpanArr = data => {
  mergeArr.forEach((key, index1) => {
    let count = 0; // 用来记录需要合并行的起始位置
    mergeObj.value[key] = []; // 记录每一列的合并信息
    data.forEach((item, index) => {
      // index == 0表示数据为第一行，直接 push 一个 1
      if (index === 0) {
        mergeObj.value[key].push(1);
      } else {
        // 判断当前行是否与上一行其值相等 如果相等 在 count 记录的位置其值 +1 表示当前行需要合并 并push 一个 0 作为占位
        if (item[key] === data[index - 1][key]) {
          mergeObj.value[key][count] += 1;
          mergeObj.value[key].push(0);
        } else {
          // 如果当前行和上一行其值不相等
          count = index; // 记录当前位置
          mergeObj.value[key].push(1); // 重新push 一个 1
        }
      }
    })
  })
}
//合并行方法
const objectSpanMethod = ({row, column, rowIndex, columnIndex}) => {
  // 判断列的属性
  if (mergeArr.indexOf(column.property) !== -1) {
    // 判断其值是不是为0
    if (mergeObj.value[column.property][rowIndex]) {
      return [mergeObj.value[column.property][rowIndex], 1]
    } else {
      // 如果为0则为需要合并的行
      return [0, 0];
    }
  }
}
/** 查询 */
const handleQuery = () => {
  orderTableLoading.value = true;
  getMyOrderPageList(params)
      .then(({data}) => {
        orderDataList.value = data.list;
        getSpanArr(data.list);
        total.value = data.totalCount;
      })
      .finally(() => {
        orderTableLoading.value = false;
      });
}

/** 重置查询 */
const resetQuery = () => {
  QueryFormRef.value.resetFields();
  handleQuery();
}

/** 行checkbox 选中事件 */
const handleSelectionChange = selection => {
  selectionIds.value = selection.map((item) => item.id);
}


/** 删除订单 */
const handleDelete = row => {
  ElMessageBox.confirm(`确认删除订单${row.id}?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    orderTableLoading.value = true;
    deleteOrderBatchByIds([row.id])
        .then(() => {
          ElMessage.success("删除成功");
          resetQuery();
        })
        .finally(() => (orderTableLoading.value = false));
  });
}
/** 批量删除 */
const handleBatchDelete = () => {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    orderTableLoading.value = true;
    deleteOrderBatchByIds(selectionIds.value)
        .then(() => {
          ElMessage.success("删除成功");
          resetQuery();
        })
        .finally(() => (orderTableLoading.value = false));
  });
}

/** 展开行查看订单详细 */
const handleRowClick = row => {
  orderDetailsStore.addOrderDetailsById(row.id, row);
  const {href} = router.resolve({
    name: "details",
    params: {id: row.id}
  })
  window.open(href, "_blank")
}
/** 查看我的订单状态 */
const handleOrderStatus = row => {
  orderDetailsStore.order = row
  console.log(orderDetailsStore.order)
  const {href} = router.resolve({
    name: "muterorder"
  })
  window.open(href, "_blank")
}

const handleCancelOrder = row => {
  toqcancel(row.id).then(() => {
    ElMessage.success("申请取消订单成功，等待卖家确定");
    resetQuery();
  })
}
/** 初始化 */
onMounted(() => {
  handleQuery();
});
onActivated(() => {
  handleQuery();
})
</script>
<style scoped>
:deep(.pagination) {
  display: flex;
  justify-content: center;
}

:deep(.el-step__icon) {
  cursor: pointer;
}

:deep(.el-button+.el-button) {
  margin-left: 0
}
</style>
